const { formatTime } = require('../../utils/util.js')
const { getApiUrl } = require('../../config/config.js')
Page({
  data: {
    userId: null, // 当前用户ID
    targetUserId: null, // 目标用户ID
    targetName: '',  // 添加目标用户名字
    messageList: [],
    inputMessage: '',
    scrollToMessage: '', // 用于消息定位
    loading: false,
    canSend: false,  // 新增：控制发送按钮状态
    theme: 'light'
  },

  onLoad(options) {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 2000)
      return
    }

    if (options.targetUserId) {
      this.setData({
        userId: userInfo.id,
        targetUserId: options.targetUserId,
        targetName: decodeURIComponent(options.targetName || '')
      })
      
      // 设置导航栏标题
      if (options.targetName) {
        wx.setNavigationBarTitle({
          title: decodeURIComponent(options.targetName)
        })
      }

      this.loadMessages()
    }
  },


  // 加载消息
  loadMessages() {
    this.setData({ loading: true })

    wx.request({
      url: getApiUrl('/message/list'),
      method: 'GET',
      data: { 
        userId: this.data.userId,
        targetUserId: this.data.targetUserId
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 格式化时间
          const messageList = res.data.data.map(msg => ({
            ...msg,
            createdAt: formatTime(new Date(msg.createdAt))
          }))
          this.setData({ 
            messageList,
            scrollToMessage: `msg-${messageList[messageList.length - 1]?.id}`
          })
          // 标记消息已读
          this.markMessagesAsRead()
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (error) => {
        console.error('Load messages failed:', error)
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({ loading: false })
      }
    })
  },

  // 发送消息
  sendMessage() {
    const content = this.data.inputMessage.trim()
    if (!content) {
      return
    }
    
    const messageData = {
      senderId: this.data.userId,
      receiverId: this.data.targetUserId,
      content: content,
      messageType: 1
    }

    wx.request({
      url: getApiUrl('/message/send'),
      method: 'POST',
      data: messageData,
      success: (res) => {
        if (res.data.code === 200) {
          const newMessage = {
            ...res.data.data,
            createdAt: formatTime(new Date(res.data.data.createdAt))
          }
          this.setData({
            messageList: [...this.data.messageList, newMessage],
            inputMessage: '',
            canSend: false,  // 发送后重置按钮状态
            scrollToMessage: `msg-${newMessage.id}`
          })
        } else {
          wx.showToast({
            title: res.data.message || '发送失败',
            icon: 'none'
          })
        }
      },
      fail: (error) => {
        console.error('Send message failed:', error)
        wx.showToast({
          title: '发送失败',
          icon: 'none'
        })
      }
    })
  },

  // 标记消息已读
  markMessagesAsRead() {
    const unreadMessages = this.data.messageList.filter(
      msg => msg.receiverId === this.data.userId && !msg.readTime
    )
    
    if (unreadMessages.length === 0) return; // 如果没有未读消息，直接返回

    console.log('Marking messages as read:', unreadMessages)
    
    unreadMessages.forEach(msg => {
      wx.request({
        url: getApiUrl(`/message/read/${msg.id}?userId=${this.data.userId}`),
        method: 'PUT',
        data: {
          readTime: new Date().toISOString()
        },
        success: (res) => {
          if (res.data.code === 200) {
            console.log(`Message ${msg.id} marked as read`)
            // 更新本地消息列表中的已读状态
            const messageList = this.data.messageList.map(item => {
              if (item.id === msg.id) {
                return { ...item, readTime: new Date().toISOString() }
              }
              return item
            })
            this.setData({ messageList })
          } else {
            console.error('Failed to mark message as read:', res.data.message)
          }
        },
        fail: (error) => {
          console.error('Mark message read failed:', error)
        }
      })
    })
  },

  // 输入框变化
  onInputMessage(e) {
    const inputValue = e.detail.value
    this.setData({
      inputMessage: inputValue,
      canSend: inputValue.trim().length > 0  // 根据输入内容判断是否可发送
    })
  },

  // 上拉加载更多
  onScrollToUpper() {
    // TODO: 实现加载更多历史消息
  }
}) 